package com.example.demo.controller.user;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.example.demo.auth.CheckLogin;
import com.example.demo.domain.dto.user.JwtTokenRespDTO;
import com.example.demo.domain.dto.user.LoginRespDTO;
import com.example.demo.domain.dto.user.UserLoginDTO;
import com.example.demo.domain.dto.user.UserRespDTO;
import com.example.demo.domain.entity.user.User;
import com.example.demo.service.user.UserService;
import com.example.demo.util.JwtOperator;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/users")
@Slf4j
public class UserController {

    @Resource
    private  UserService userService;

    @Resource
    private JwtOperator jwtOperator;

    @Autowired
    private WxMaService wxMaService;

    @GetMapping("/{id}")
    @CheckLogin
    public User findById(@PathVariable Integer id) {
        log.info("我被请求了...");
        return this.userService.findById(id);
    }

    /**
     * 模拟生成token(假的登录)
     */
    @GetMapping("/gen-token")
    public String genToken() {
        Map<String, Object> userInfo = new HashMap<>(3);
        User user = new User(1, "111", "Jack", "admin", "a.png", new Date(), new Date(), 11);
        // 颁发token
        userInfo.put("id", user.getId());
        userInfo.put("wxNickname", user.getWxNickname());
        userInfo.put("role", user.getRoles());

        return this.jwtOperator.generateToken(userInfo);
    }

    @PostMapping("/login")
    public LoginRespDTO login(@RequestBody UserLoginDTO loginDTO) throws WxErrorException {
        // 微信小程序服务端校验是否已经登录的结果
//        WxMaJscode2SessionResult result = this.wxMaService.getUserService()
//                .getSessionInfo(loginDTO.getCode());
//
//        // 微信的openId，用户在微信这边的唯一标示
//        String openid = result.getOpenid();

        if (loginDTO.getCode().equals("111")) {
            // 看用户是否注册，如果没有注册就（插入）
            // 如果已经注册
            // User user = this.userService.login(loginDTO, openid);
            User user = new User(1, "111", "Jack", "admin", "a.png", new Date(), new Date(), 11);
            // 颁发token
            Map<String, Object> userInfo = new HashMap<>(3);
            userInfo.put("id", user.getId());
            userInfo.put("wxNickname", user.getWxNickname());
            userInfo.put("role", user.getRoles());

            String token = jwtOperator.generateToken(userInfo);

            log.info(
                    "用户{}登录成功，生成的token = {}, 有效期到:{}",
                    loginDTO.getWxNickname(),
                    token,
                    jwtOperator.getExpirationTime()
            );

            // 构建响应
            return LoginRespDTO.builder()
                    .user(
                            UserRespDTO.builder()
                                    .id(user.getId())
                                    .avatarUrl(user.getAvatarUrl())
                                    .bonus(user.getBonus())
                                    .wxNickname(user.getWxNickname())
                                    .build()
                    )
                    .token(
                            JwtTokenRespDTO.builder()
                                    .expirationTime(jwtOperator.getExpirationTime().getTime())
                                    .token(token)
                                    .build()
                    )
                    .build();
        } else {
            return null;
        }
    }
}
